<route lang="json5" type="page">
  {
    style: {
      navigationBarTitleText: '选择班级',
    },
    anonymous: false
  }
</route>

<script lang="ts" setup>
import StudentClassCard from '@/components/StudentClassCard.vue'
import { useUserStore } from '@/stores'
import type { ClassSelectType } from '@/apis'
import { ClassApi, ShopApi } from '@/apis'
import ProPicker from '@/components/ProPicker.vue'
import { listArrangeTemplate, listCampus, listTeacher, listTimeTemplate } from '@/apis/common'

const userStore = useUserStore()

const loading = ref(false)
const keyword = ref('')
const selectType = ref<ClassSelectType>()
const query = ref<ShopApi.ShopClassQuery>()
const records = ref([])

const getClassList = async () => {
  let res = []
  loading.value = true
  try {
    if (selectType.value === 'original') {
      res = await ClassApi.getStudentClassList({ studentId: userStore.currentStudent.id })
    } else {
      res = (await ShopApi.getShopClassList(query.value)).filter(item => item.id !== query.value.originalClassId)
    }
    records.value = res.map((item) => {
      return {
        select: false,
        item,
      }
    })
    keyword.value = ''
    query.value.keyword = ''
  } finally {
    loading.value = false
  }
}

// 过滤更多
const filterMoreShow = ref(false)
const openPopup = () => {
  filterMoreShow.value = true
}
const closePopup = () => {
  filterMoreShow.value = false
}

const selectHandle = (item) => {
  records.value.forEach(it => it.select = false)
  item.select = true
}

const confirm = () => {
  const selectedClassList = records.value.filter(item => item.select).map(item => item.item)
  if (selectedClassList.length) {
    if (selectType.value === 'original') {
      uni.setStorageSync('originalClass', JSON.stringify(selectedClassList))
    } else {
      uni.setStorageSync('targetClass', JSON.stringify(selectedClassList))
    }
    uni.navigateBack()
  } else {
    uni.showToast({
      title: '请选择班级',
      icon: 'none',
    })
  }
}

const campusList = ref([])
const getCampusList = async () => {
  campusList.value = await listCampus()
}

const arrangeTemplateList = ref([])
const getArrangeTemplateList = async (query) => {
  arrangeTemplateList.value = (await listArrangeTemplate(query)).map((item) => {
    return {
      ...item,
      // label: `${item.name}(${item.startDate}~${item.endDate})`,
      label: item.fullName,
    }
  })
}

const timeTemplateList = ref([])
const getTimeTemplateList = async () => {
  timeTemplateList.value = await listTimeTemplate()
}

const teacherList = ref([])
const getTeacherList = async () => {
  teacherList.value = await listTeacher()
}

const resetHandle = () => {
  keyword.value = ''
  query.value.keyword = ''
  getClassList()
  closePopup()
}

const searchHandle = () => {
  query.value.keyword = keyword.value
  // 时间段筛选条件未加入到query参数中，
  // 只需要将dateRange的值赋值给query对应字段即可 (后端需要要的字段)
  // 需要先判断下dateRange的长度
  // 如 query.value.beginDate = dayjs(dateRange.value[0]).format('YYYY-MM-DD')
  // query.value.endDate = dayjs(dateRange.value[1]).format('YYYY-MM-DD')
  getClassList()
  closePopup()
}

onLoad((options) => {
  if (options.type) {
    selectType.value = options.type
  }

  const params = JSON.parse(JSON.stringify(options))
  delete params.type
  query.value = params
  query.value.studentId = userStore.currentStudent.id

  if (selectType.value === 'target') {
    const query1 = {
      classYear: params.classYear,
      term: params.term,
      grade: params.grade,
    }
    getCampusList()
    getArrangeTemplateList(query1)
    getTimeTemplateList()
    getTeacherList()
  }
  getClassList()
})
</script>

<template>
  <view v-if="loading" class="flex-row-center-center bg-white page">
    <wd-loading color="#33AD7C" />
  </view>
  <template v-else>
    <view v-if="selectType !== 'original'" class="filter-panel w-full flex-row-between-center bg-white px-4" style="height: 88rpx">
      <!-- 校区 -->
      <view class="filter-tab-item flex-row-center-center flex-1">
        <ProPicker v-model="query.campusId" placeholder="校区" :options="campusList" @change="getClassList" />
        <wd-icon name="caret-down-small" size="22px" />
      </view>
      <!-- 期段 -->
      <view class="filter-tab-item flex-row-center-center flex-1">
        <ProPicker v-model="query.arrangeTemplateId" placeholder="期段" :options="arrangeTemplateList" @change="getClassList" />
        <wd-icon name="caret-down-small" size="22px" />
      </view>
      <!-- 时间段 -->
      <view class="filter-tab-item flex-row-center-center flex-1">
        <ProPicker v-model="query.timeTemplateId" placeholder="时间段" :options="timeTemplateList" @change="getClassList" />
        <wd-icon name="caret-down-small" size="22px" />
      </view>
      <!-- 老师 -->
      <view class="filter-tab-item flex-row-center-center flex-1">
        <ProPicker v-model="query.leadTeacherId" placeholder="主讲老师" :options="teacherList" @change="getClassList" />
        <wd-icon name="caret-down-small" size="22px" />
      </view>
      <!-- 更多 -->
      <!-- <view class="flex-row-center-center flex-1" @click="openPopup">
        <text class="filter-tab-more mr-1">
          筛选
        </text>
        <wd-icon name="filter" />
      </view> -->
    </view>
    <!-- <view v-if="selectType !== 'original'" style="height: 88rpx;" /> -->
    <view class="content px py" style="padding-bottom: 120rpx;">
      <view v-for="(item, index) in records" :key="item" class="mt-[24rpx]" :style="index === 0 ? 'margin-top:0' : ''">
        <view @click="selectHandle(item)">
          <StudentClassCard :active="item.select" :data="item.item" />
        </view>
      </view>
      <view v-if="!records.length">
        <wd-status-tip image="content" tip="暂无数据" />
      </view>
    </view>

    <view class="footer">
      <view class="px-[30rpx] py-[12rpx]">
        <wd-button block type="success" :round="false" @click="confirm()">
          确定
        </wd-button>
      </view>
    </view>

    <wd-popup v-model="filterMoreShow" position="right" custom-style="width: 70%;">
      <view class="scroll-view h-[100%] flex flex-col bg-white">
        <view class="flex items-center !pl-[32rpx]">
          <view class="bg-white line-height-44px" @click="closePopup">
            <wd-icon name="close" size="22px" />
          </view>
          <view class="flex-1 text-center font-size-[30rpx] line-height-44px">
            条件筛选
          </view>
        </view>
        <view class="h-1px bg-[#eee]" />
        <view class="flex flex-1 flex-col pt-[24rpx]">
          <scroll-view class="flex-1 px-[32rpx]" scroll-y="true">
            <view class="font-size-[28rpx]">
              <view>老师:</view>
              <view class="mt-[10rpx] border-rd-[16rpx] bg-[#f8f8f8] px-20rpx py-[12rpx]">
                <wd-input
                  v-model="keyword"
                  prefix-icon="search"
                  placeholder="请输入老师名字"
                />
              </view>
            </view>
          </scroll-view>
          <view class="flex items-center gap-[20rpx] px py font-size-[28rpx]" style="box-sizing: border-box;">
            <view class="flex-1 border-rd-[12rpx] bg-[#f2f2f2] px-20rpx py-[12rpx] text-center" @click="resetHandle">
              重置
            </view>
            <view class="flex-1 border-rd-[12rpx] bg-[#5aab80] px-20rpx py-[12rpx] text-center color-[#fff]" @click="searchHandle">
              确定
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
  </template>
</template>

<style lang="scss" scoped>
  .content {
    height: calc(100vh - 160rpx) !important;
    overflow: scroll;
  }
  .filter-panel {
    // position: fixed;
    // left: 0;
    // top: 0;
    // right: 0;
    position: sticky;
  }
  .footer {
    position: fixed;
    left: 0px;
    bottom: 0px;

    height: 160rpx;
    width: 100%;
    background: white;
    box-shadow: 0px -4px 4px 0px #0000000D;

  }
  .filter-tab-more {
    position: relative;
    padding-left: 40rpx;
  }

  .filter-tab-more::before {
    content: "";
    width: 2px;
    height: 16px;
    position: absolute;
    top: 3px;
    left: 0;
    background: black;
  }
  :deep(.wd-input),:deep(.wd-input__icon),:deep(.wd-picker__cell) {
    background-color: transparent !important;
  }
</style>
